package com.hxxy.wyp.petsLover.security;

import cn.dev33.satoken.stp.StpUtil;
import com.hxxy.wyp.petsLover.common.entities.Admin;
import com.hxxy.wyp.petsLover.common.entities.User;
import com.hxxy.wyp.petsLover.common.services.base.backend.AdminService;
import com.hxxy.wyp.petsLover.common.services.base.fronted.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName SecurityContextFrontUser
 * @Description TODO
 * @Author wyp
 * @Date 2023/1/14 17:44
 * @Version 1.0
 */
@Component
public class SecurityContextFrontUser {

    // 当前线程的用户key
    public static final String ATTR_USER = "_currentFrontUser";

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private AdminService adminService;

    @Autowired
    private UserService userService;


    /**
     * 获取登录的用户id
     */
    public String getLoginUserId() {
        if (StpUtil.isLogin()) {
            return StpUtil.getLoginIdAsString();
        } else {
            return null;
        }
    }

    /**
     * 设置后台登录用户信息
     */
    public void setUserInfo(User user) {
        if (user == null) {
            return;
        }

        if (StpUtil.isLogin()) {
            request.setAttribute(ATTR_USER, user);
        }
    }


    /**
     * 获取后台登录用户信息
     */
    public User getUserInfo() {
        if (!StpUtil.isLogin()) {
            return null;
        }
        User user = (User) request.getAttribute(ATTR_USER);
        if (user != null) {
            return user;
        }
        String userId = getLoginUserId();
        long userIdLong = Long.parseLong(userId);
        if (userId == null) {
            return null;
        }
        user = userService.getById(userIdLong);
        if (user == null) {
            return null;
        }
        setUserInfo(user);
        return user;
    }


    /**
     * 清除登录用户信息
     */
    public void clearUserInfo() {
        request.removeAttribute(ATTR_USER);
    }


    /**
     * 是否已登录
     */
    public boolean isLogin() {
        return StpUtil.isLogin();
    }


    /**
     * 获取token
     */
    public String getToken() {
        return StpUtil.getTokenValue();
    }


    /**
     * get user ip address
     */
    public String getUserIp() {
        // try get real ip if user use proxy
        String ip = request.getHeader("X-Forwarded-For");

        if (!isValidIp(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (!isValidIp(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (!isValidIp(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (!isValidIp(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (!isValidIp(ip)) {
            ip = request.getRemoteAddr();
        }

        if (isValidIp(ip) && StringUtils.indexOf(ip, ",") > 0) {
            String[] ips = ip.split(",");
            for (String s : ips) {
                if (!("unknown".equalsIgnoreCase(s))) {
                    ip = s;
                    break;
                }
            }
        }
        return ip;
    }

    private boolean isValidIp(String ip) {
        return StringUtils.isNotEmpty(ip) && !StringUtils.equalsIgnoreCase("unknown", ip);
    }


}
